package com.jeesite.modules.isys.xmqtt.client;


import cn.hutool.extra.spring.SpringUtil;
import com.jeesite.modules.isys.xmqtt.ann.XSubscription;
import com.jeesite.modules.isys.xmqtt.hander.XHander;


import java.util.*;

public class XSubscriptions {

    private static HashMap<String,List<XHander>> handersMap = new HashMap<>();

   static void InitData(){
        Map<String, Object> handers = SpringUtil.getApplicationContext().getBeansWithAnnotation(XSubscription.class);

        //获取名字
        for (Object xHander : handers.values()){

            XSubscription xSubscription = xHander
                    .getClass()
                    .getAnnotation(XSubscription.class);
            if (xSubscription!=null){

                //获取map内容
                List<XHander> handerList = handersMap.get(xSubscription.topic());

                if (handerList != null){
                    handerList.add((XHander) xHander);
                    handersMap.put(xSubscription.topic() ,handerList);
                }else {
                    handerList = new ArrayList<>();
                    handerList.add((XHander) xHander);
                    handersMap.put(xSubscription.topic() ,handerList);
                }
            }
        }
        Comparator<XHander> comparatorXHander =new Comparator <XHander>(){
            public int compare(XHander p1,XHander p2){
                return Integer.compare(p2.getOrder(), p1.getOrder());
            }
        };

        for (List<XHander> list : handersMap.values()){
            list.sort(comparatorXHander);
        }
    }

    public  static  List<XHander> getHanderList(String topic){
        if (handersMap.isEmpty()){
            InitData();
        }

        return  handersMap.get(topic);
    }


    public static Set<String> getTopics(){
        if (handersMap.isEmpty()){
            InitData();
        }

        return  handersMap.keySet();
    }


}
